package com.booktrading.util;

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtil {

    /**
     * 上传文件并返回文件URL
     * @param file 文件
     * @param uploadDir 上传目录
     * @return 文件URL
     * @throws IOException IO异常
     */
    public static String saveFile(MultipartFile file, String uploadDir) throws IOException {
        // 创建上传目录
        File uploadDirFile = new File(uploadDir);
        if (!uploadDirFile.exists()) {
            if (!uploadDirFile.mkdirs()) {
                throw new IOException("无法创建上传目录");
            }
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path targetPath = uploadDirFile.toPath().resolve(fileName);
        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回相对路径
        return "/booktrading/static/uploads/" + fileName;
    }
    
    /**
     * 从本地路径上传文件
     * @param localFilePath 本地文件路径
     * @param uploadDir 上传目录
     * @return 文件URL
     * @throws IOException IO异常
     */
    public static String saveFileFromLocalPath(String localFilePath, String uploadDir) throws IOException {
        // 创建上传目录
        File uploadDirFile = new File(uploadDir);
        if (!uploadDirFile.exists()) {
            if (!uploadDirFile.mkdirs()) {
                throw new IOException("无法创建上传目录");
            }
        }
        
        File localFile = new File(localFilePath);
        if (!localFile.exists() || !localFile.isFile()) {
            throw new IOException("本地文件不存在: " + localFilePath);
        }
        
        // 生成唯一文件名
        String originalFilename = localFile.getName();
        String extension = getFileExtension(originalFilename);
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path targetPath = uploadDirFile.toPath().resolve(fileName);
        Files.copy(localFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回相对路径
        return "/booktrading/static/uploads/" + fileName;
    }
    
    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            return ".jpg"; // 默认扩展名
        }
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex == -1) {
            return ".jpg"; // 默认扩展名
        }
        return fileName.substring(lastDotIndex).toLowerCase();
    }
} 